<template>
  <div class="teacher">
    <h2>讲师管理</h2>
    <div class="search_box">
      <el-form :inline="true" ref="resetForm" :model="student" class="demo-form-inline">
        <el-form-item label="学生状态" prop="state">
          <el-select v-model="student.state" placeholder="请选择学生状态">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生名称" prop="name">
          <el-input v-model="student.name" placeholder="请输入学生名称"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="student.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button plain icon="el-icon-search" @click="search">搜索</el-button>
          <el-button plain icon="el-icon-bottom-left" @click="resetForm('resetForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="content">
      <div class="btn_box">
        <el-button type="primary" @click="addStudent">新增学员</el-button>
        <el-button type="primary">批量导入</el-button>
        <el-button type="primary">批量导出</el-button>
        <el-button type="primary">查看报表</el-button>
        <el-button type="danger" @click="delMore">批量删除</el-button>
      </div>
      <div>
        <el-table
          stripe
          :data="list"
          border
          @selection-change="selectChange"
          style="width: 100%">
          <el-table-column
            type="selection"
            width="80"
            align="center">
          </el-table-column>
          <el-table-column
            prop="nickname"
            label="学生名称"
            align="center">
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="手机号"
            align="center">
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="scope">
              {{scope.row.status === 1? '启用' : "禁用"}}
            </template>
          </el-table-column>
          <el-table-column
            prop="created_at"
            label="创建时间"
            align="center">
            <template slot-scope="scope">
              <span>{{scope.row.created_at | timeFormat}}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="150"
            align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small">查看</el-button>
              <el-button type="danger" size="small" @click="delData(scope.row)">删除</el-button>
              <el-button type="text" size="small" @click="exit(scope.row, scope.$index)">编辑</el-button>
            </template> 
          </el-table-column>
        </el-table>
      </div>
      
    </div>
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.pageIndex"
      :page-sizes="[8, 10, 30, 60]"
      :page-size="params.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totle">
    </el-pagination>

    <el-dialog
      title="新增数据"
      :visible.sync="dialogVisible"
      width="30%">
      <div>
        <el-form ref="addForm" :rules="rules" :model="form" label-width="80px">
          <el-form-item label="学生名称" prop="nickname">
            <el-input v-model="form.nickname"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input type="text" v-model="form.mobile"></el-input>
          </el-form-item>
          <el-form-item label="学生状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio label="启用" :value="1"></el-radio>
              <el-radio label="禁用" :value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="创建时间">
             <el-date-picker
             format="yyyy-MM-dd HH:mm:ss"
             value-format="yyyy-MM-dd HH:mm:ss"
              v-model="form.created_at"
              type="datetime"
              placeholder="选择日期事件">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="certainAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getStudents } from '../utils/api'
export default {
  name: 'teacher',
  data() {
    return {
      student: {
        state: null,
        name: '',
        mobile: ''
      },
      list: [],
      params: {
        pageIndex: 1,
        pageSize: 10
      },
      totle: 0,
      originList: [],
      // 保存勾选中的数据
      delArr: [],
      dialogVisible: false,
      form: {
        nickname: '',
        mobile: '',
        status: null,
        created_at: ''
      },
      rules: {
        nickname: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入学生名称'
          }
        ],
        mobile: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入电话号码'
          }
        ],
        status: [
          {
            required: true,
            trigger: 'blur',
            message: '请选择学生状态'
          }
        ]
      },
    // true表示新增 false表示编辑
      isAdd: true,
      exitData: 0
      
    }
  },
  filters: {
    timeFormat(val) {
      var time = val * 1000
      var date = new Date(time)
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      month = month > 9? month : '0' + month 
      var day = date.getDate()
      day = day > 9? day : '0' + day 
      var h = date.getHours()
      h = h > 9 ? h : '0' + h
      var m = date.getMinutes()
      m = m > 9 ? m : '0' + m
      var s = date.getSeconds()
      s = s > 9? s : '0' + s
      return `${year}-${month}-${day} ${h}:${m}:${s}`
    }
  },
  created() {
    this.getNewList(this.params)
  },
  methods: {
    // 定义获取学生信息的函数
    getNewList(params) {
      getStudents(params).then(res => {
          // console.log(res)
          this.list = res.newArr
          this.totle = res.totle
          this.originList = JSON.stringify(res.newArr)
      })
    },

    // 每页显示多少条数据变化时触发的函数
    handleSizeChange(size) {
      this.params.pageSize = size
      this.getNewList(this.params)
    },

    // 页码变化时触发的逻辑
    handleCurrentChange(page) {
      this.params.pageIndex = page
      this.getNewList(this.params)
    },

    // 点击进行数据搜索
    search() {
        this.list = JSON.parse(this.originList)
        if(this.student.state !== null) {
          this.list = this.list.filter((item, index, array) => {
            return item.status === this.student.state
          })
        }

        if(this.student.name !== '') {
           this.list = this.list.filter((item, index, array) => {
             return item.nickname.includes(this.student.name)
          })
        }


        if(this.student.mobile !== '') {
          this.list = this.list.filter((item, index, array) => {
             return item.mobile.includes(this.student.mobile)
          })
        }
    },

    resetForm(form) {
      this.$refs[form].resetFields();
      this.list = JSON.parse(this.originList) 
    },

    // 删除数据
    delData(data) {
      this.$confirm('是否确认删除该数据？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认删除',
        cancelButtonText: '取消删除'
      }).then(() => {
        this.list.forEach((item, i) => {
          if(item.uid === data.uid) {
            this.list.splice(i, 1)
          }
        })
        this.$message({
          type: 'success',
          message: '删除成功'
        });
      }).catch(action => {});
    },

    // 表格数据勾选事件
    selectChange(val) {
      // console.log(val)
      this.delArr = val
    },
    // 批量删除
    delMore() {
      for(var i = this.list.length - 1; i >= 0; i--) {
        this.delArr.forEach((item) => {
          if(item.uid === this.list[i].uid) {
            this.list.splice(i, 1)
          }
        })
      }
    },

  // 新增数据
    addStudent(){
      this.dialogVisible = true
      this.isAdd = true
    },

    certainAdd() {
      this.$refs['addForm'].validate((valid) => {
        // valid 值是true表示表单验证通过
        if (valid) {
          if(this.isAdd) {
            this.list.unshift(this.form)
            this.form = {
              nickname: '',
              mobile: '',
              status: null,
              created_at: ''
            }
          } else {
            this.list[this.exitData] = this.form
          }
          this.dialogVisible = false
        } else {
          console.log('error submit!!');
          return false;
        }
      })
      
      
    },

    exit(data, i) {
      // console.log(data)
      this.exitData = i
      this.form = {
        nickname: data.nickname,
        mobile: data.mobile,
        status: data.status,
        created_at: data.created_at
      }
      this.dialogVisible = true
      this.isAdd = false
    }
  },
  // watch数据监听的方法 数据发生变化时可以出发对应的逻辑
  watch: {
    // 基本数据类型可以直接进行监听
    totle(to, from) {
      // from是数据变化之前的值 to数据变化之后的值
      // console.log(to, from)
    },

    'student.state'(to, from) {
      console.log('变化了')
    }
  }
}
</script>
<style lang="scss" scoped>
  h2{
    line-height: 50px;
    border-bottom: 2px solid #ccc;
    padding-left: 10px;
    font-weight: bold;
    margin-bottom: 20px;
  }
  .search_box{
    padding-left: 10px;
  }
  .content{
    padding: 10px;
    padding-right: 20px;
    margin-bottom: 20px;
    .btn_box{
      margin-bottom: 20px;
    }
  }
</style>
